﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.IO;

public class SaveManager : MonoBehaviour
{
    public static SaveManager Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = GameObject.FindObjectOfType<SaveManager>();
            }
            if (!_Instance)
            {
                GameObject obj = new GameObject("SaveManager");
                _Instance = obj.AddComponent<SaveManager>();
            }
            return _Instance;
        }
        set
        {
            _Instance = value;
        }
    }
    private static SaveManager _Instance;

    public string filePath;

    private void Awake()
    {
        if (!File.Exists(Application.dataPath + "/Save"))
            Directory.CreateDirectory(Application.dataPath + "/Save");
        filePath = Application.dataPath + "/Save/save.json";
    }

    public void SaveGame()
    {
        Save save = MapManager.Instance.CreateSave();
        string saveStr = JsonMapper.ToJson(save);
        StreamWriter sw = new StreamWriter(filePath);
        sw.Write(saveStr);
        sw.Close();
    }

    public void LoadGame()
    {
        ConstOfMap.loadgame = true;
        StreamReader sr = new StreamReader(filePath);
        string jsonStr = sr.ReadToEnd();
        sr.Close();
        ConstOfMap.save = JsonMapper.ToObject<Save>(jsonStr);
    }
    public bool HasSaveFile()
    {
        return File.Exists(filePath);
    }
}
